<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
       function buildTree(data) {
        const treeMap = {};
        const tree = [];

        data.forEach(item => {
            treeMap[item.id] = { ...item, children: [] };

            if (item.parentId === null || !treeMap[item.parentId]) {
                tree.push(treeMap[item.id]);
            } else {
                console.log(treeMap);
                treeMap[item.parentId].children.push(treeMap[item.id]);
                console.log(treeMap);
            }
        });
        console.log(tree);
        return tree;
    }

// Example usage
const data = [
    { id: 1, parentId: null, name: 'Node 1' },
    { id: 2, parentId: 1, name: 'Node 2' },
    { id: 3, parentId: 1, name: 'Node 3' },
    { id: 4, parentId: 2, name: 'Node 4' },
    { id: 5, parentId: 2, name: 'Node 5' },
    { id: 6, parentId: null, name: 'Node 6' },
    { id: 7, parentId: 5, name: 'Node 6' },
];

const tree = buildTree(data);

    </script>
</body>
</html>